const getUser = () => {
	return new Promise((resolve, reject) => {
		uniCloud.callFunction({
			name: 'getUser',
			success: (data) => {
				const res = data.result.data
				if (Array.isArray(res)) {
					resolve(res);
				} else {
					reject()
				}
			},
			fail: () => {
				reject()
			}
		});
	})
}

const addUser = (acc, pwd) => {
	return new Promise((resolve, reject) => {
		uniCloud.callFunction({
			name: 'addUser',
			data: {
				acc,
				pwd
			},
			success: (data) => {
				const res = data.result
				// console.log('res?.id', res);
				if (typeof res?.id === 'string' && res?.id) {
					resolve(res);
				} else {
					reject()
				}
			},
			fail: () => {
				reject()
			}
		});
	})
}

export const loginOrRegister = async (acc, pwd) => {
	const allUser = await getUser()
	const user = allUser.find(o => o.acc === acc)
	if (user) {
		return user
	} else {
		const newId = await addUser(acc, pwd)
		if (newId) {
			return (await getUser()).find(o => o.acc === acc)
		} else {
			return
		}
	}
}